package com.usian.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.model.article.pojos.ApAuthor;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.user.dtos.FollowBehaviorDto;
import com.usian.model.user.dtos.UserRelationDto;
import com.usian.model.user.pojos.ApUser;
import com.usian.model.user.pojos.ApUserFan;
import com.usian.model.user.pojos.ApUserFollow;
import com.usian.user.feign.ApAuthorFeign;
import com.usian.user.mapper.ApUserFollowMapper;
import com.usian.user.service.ApUserFanService;
import com.usian.user.service.ApUserFollowService;
import com.usian.user.service.ApUserService;
import com.usian.utils.threadlocal.AppThreadLocalUtils;
import org.codehaus.groovy.ast.stmt.ReturnStatement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApUserFollowServiceImpl extends ServiceImpl<ApUserFollowMapper, ApUserFollow> implements ApUserFollowService {

    @Autowired
    private ApAuthorFeign apAuthorFeign;
    @Autowired
    private ApUserFanService apUserFanService;
    @Autowired
    private ApUserService apUserService;
    @Autowired
    private KafkaTemplate kafkaTemplate;

    @Override
    public ResponseResult follow(UserRelationDto dto) {

        //1:校验参数
        if(dto==null || dto.getAuthorId()==null ||dto.getArticleId()==null ||dto.getOperation()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2：远程调用 查作者信息
        ApAuthor apAuthor = apAuthorFeign.findById(dto.getAuthorId());
        if(apAuthor!=null){

            //3:关注 0  取消关注 1
            ApUser apUser = AppThreadLocalUtils.getUser();
            Integer userId=null;
            if(apUser!=null){
                userId = apUser.getId();
            }
            if(dto.getOperation()==0){
                //关注
                boolean result = follows(userId,dto.getAuthorId(),apAuthor.getName(),dto.getArticleId());
                if(!result){
                    return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
                }
            }else if(dto.getOperation()==1){
                //取消关注
                cancelFollows(userId,dto.getAuthorId(),apAuthor.getName());
            }
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
    //取消关注
    public void cancelFollows(Integer userId,Integer followId,String followName){
        //follow
        this.remove(Wrappers.<ApUserFollow>lambdaQuery().eq(ApUserFollow::getUserId, userId)
                .eq(ApUserFollow::getFollowId, followId));

        //fan
        apUserFanService.remove(Wrappers.<ApUserFan>lambdaQuery()
                .eq(ApUserFan::getUserId, followId).eq(ApUserFan::getFansId, userId));
    }

    //关注
    public boolean follows(Integer userId,Integer followId,String followName,Long articleId){
        boolean flag =true;

        //follow 查再新增
        ApUserFollow apUserFollow = this.getOne(Wrappers.<ApUserFollow>lambdaQuery().eq(ApUserFollow::getUserId, userId)
                .eq(ApUserFollow::getFollowId, followId));
        if(apUserFollow==null){
            ApUserFollow apUserFollow1 =new ApUserFollow();
            apUserFollow1.setUserId(userId);
            apUserFollow1.setFollowId(followId);
            apUserFollow1.setFollowName(followName);
            apUserFollow1.setLevel((short)1);
            apUserFollow1.setIsNotice(true);
            apUserFollow1.setCreatedTime(new Date());
            this.save(apUserFollow1);

            //fan
            ApUserFan apUserFan = apUserFanService.getOne(Wrappers.<ApUserFan>lambdaQuery()
                    .eq(ApUserFan::getUserId, followId).eq(ApUserFan::getFansId, userId));
            if(apUserFan==null){
                apUserFan = new ApUserFan();
                apUserFan.setUserId(followId);
                apUserFan.setFansId(userId.longValue());

                ApUser apUser = apUserService.getById(userId);
                if(apUser!=null){
                    apUserFan.setFansName(apUser.getName());
                }
                apUserFan.setLevel((short)0);
                apUserFan.setIsDisplay(true);
                apUserFan.setIsShieldLetter(false);
                apUserFan.setIsShieldComment(false);
                apUserFan.setCreatedTime(new Date());
                apUserFanService.save(apUserFan);
            }

            //关注完毕后来记录用户关注行为  kafka发消息
            FollowBehaviorDto dto =new FollowBehaviorDto();
            dto.setUserId(userId);
            dto.setFollowId(followId);
            dto.setArticleId(articleId);
            kafkaTemplate.send("followBehavior", JSON.toJSONString(dto));
            System.out.println("用户关注行为发送消息："+JSON.toJSONString(dto));
        }else{
            flag=false;
        }
        return flag;
    }
}
